package com.example.l3.ktm.DownloadUtility;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONParser {
	
	private InputStream _inputStream;
	private Writer _writer = new StringWriter();
	private char[] _buffer = new char[1024];
	public JSONParser(String pathSrc){		
	}
	
	public JSONParser(InputStream input){
		this._inputStream  = input;
	}
	
	public Vector<String[]> parseJSON() {
		Vector<String[]> urls = new Vector<String[]>(2);
		
		JSONObject jsonObject;
		JSONArray arrayURL;
		
		// read  json file in asset folder
		try {
			jsonObject = new JSONObject(readJSONFile());
			// parse jsonString to vector url
			arrayURL = jsonObject.getJSONArray("urls");
			
			for(int i = 0; i < arrayURL.length(); i++){
				JSONObject c = arrayURL.getJSONObject(i); 
				String url = c.getString("url");
				String title = c.getString("title");
				
				String[] objectUrl = new String[2];
				objectUrl[0] = title;
				objectUrl[1] = url;
				
				urls.add(objectUrl);
			}
			
		}  catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		
		
		return urls;
	}
	
	protected String readJSONFile() throws IOException {
		String jsonString;
		try {
			Reader reader = new BufferedReader(new InputStreamReader(_inputStream, "UTF-8"));
			int n;
		    while ((n = reader.read(_buffer)) != -1) {
		        _writer.write(_buffer, 0, n);
		    }
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		finally{
			_inputStream.close();			
		}
		
		if (_writer.toString() != null) {
			jsonString = _writer.toString();
		} else {
			jsonString = null;
		}
		
		return jsonString;
	}
}
